package controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.FullJobState;
import beans.RunningTask;
import engine.BIEngine0_1.AlgorithmThread;
import engine.BIEngine0_1.TaskThread;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class GetAlgorithmState
 */
public class GetAlgorithmState extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetAlgorithmState() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			try {
				String taskHash = request.getParameter("taskHash");
				JSONArray results = new JSONArray();
				TaskThread task = RunningTask.TASKMAP.getTask(taskHash);
				for(Map.Entry<String,AlgorithmThread> one:task.runningTaskBean.runningAlgorithms.entrySet()){
					AlgorithmThread algorithmThread = one.getValue();
					JSONObject result = new JSONObject();
					JSONArray jobs = new JSONArray();
					for(FullJobState state:algorithmThread.fullJobStates){
						JSONObject job = new JSONObject();
						job.put("jobId", state.getJobId());
						job.put("jobName", state.getJobName());
						jobs.add(job);
					}
					result.put("blockId", algorithmThread.algorithmHash);
					result.put("jobs", jobs.toString());
					results.add(result);
				}
				response.getWriter().write(results.toString());
			} catch (NullPointerException e) {
				e.printStackTrace();
				response.getWriter().write("error");
			}
	}
}
